﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace TaskSyncOperation
{
    internal class ArrayHelper
    {
        internal static string[] GetArray(object source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source), "Source cannot be null.");
            }

            if (source is string stringValue)
            {
                return new[] { stringValue }; // 如果是单个字符串，转换为单元素数组
            }

            if (source is string[] stringArray)
            {
                return stringArray; // 如果已经是字符串数组，直接返回
            }

            if (source is IEnumerable<string> stringEnumerable)
            {
                return stringEnumerable.ToArray(); // 如果是 IEnumerable<string>，转换为数组
            }

            if (source is JsonArray jsonArray)
            {
                return jsonArray.Select(item => item?.ToString()).ToArray(); // 如果是 JsonArray，转换为字符串数组
            }

            if (source is ArrayList arrayList)
            {
                List<string> stringList = new List<string>();
                
                foreach (var item in arrayList)
                {
                    if (item is string strItem)
                    {
                        stringList.Add(strItem); // 如果是字符串，添加到列表
                    }
                    else if (item != null)
                    {
                        stringList.Add(item.ToString()); // 其他类型转换为字符串
                    }
                }

               return stringList.ToArray(); // 转换为字符串数组并返回
            }

            throw new ArgumentNullException(nameof(source), "Source cannot be cast. string,string[],IEnumerable<string>,JsonArray,ArrayList is required.");
        }
    }
}
